// 运维部门管理 新增/编辑
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { FormInstance } from 'element-plus'
import type {
  OperationsManageOption,
  formOperationsManageStateType,
  operationsManageTableListDataItemType
} from '../typings'
import { defineComponent, ref, reactive, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElButton,
  ElMessage,
  ElSpace,
  ElLink,
  ElIcon,
  ElSelect,
  ElOption,
  ElTag,
  ElScrollbar
} from 'element-plus'
import { CirclePlusFilled } from '@element-plus/icons-vue'
import ProSaasTable from '~/components/ProSaasTable'
import styles from '~/pages/oam/index.module.scss'

export default defineComponent({
  name: 'OperationsManageOption',
  props: ['visible', 'title', 'rowId', 'department', 'addList', 'nowDynamicTags'],
  emits: ['cancel', 'departmentAjax', 'refreshTable', 'getDeptWorkareaListAjax'],
  setup(props: OperationsManageOption, { emit }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>() // 表单
    const dynamicProSaasTableRef = ref<ProSaasTableExposeType>() // 新增/编辑 对应工区 列表
    const formAddDynamicTags = ref('')
    const formState = reactive<formOperationsManageStateType['form']>({})

    // 监听tag变化
    watch(
      () => formState.dynamicTags,
      () => {
        formAddDynamicTags.value = JSON.parse(JSON.stringify(formState.dynamicTags))
      },
      {
        deep: true
      }
    )
    watch(
      () => formAddDynamicTags.value,
      (newValue, oldValue) => {
        const delDynamicTags = [] // 不同的值
        for (let i = 0; i < oldValue!.length; i++) {
          if (newValue?.indexOf(oldValue![i]) === -1) {
            delDynamicTags.push(oldValue![i])
          }
        }
        const index = props.nowDynamicTags?.indexOf(delDynamicTags[0])
        if (delDynamicTags.length > 0 && index !== -1) {
          props.nowDynamicTags!.splice(index!, 1) /// 去掉 delDynamicTags
        }
        emit('getDeptWorkareaListAjax', props.nowDynamicTags) // 更新当前工区
      },
      {
        deep: true
      }
    )

    onMounted(() => {
      originalContent()
    })

    // 初始化 编辑 查看
    const originalContent = async () => {
      if (props.rowId) {
        const res = await store.dispatch('order/GetDeptConfigView', { id: props.rowId })
        // 原内容
        if (res?.code === 200) {
          if (res.data.id) {
            // 工区id
            formState.id = res.data.id
          } else {
            formState.id = ''
          }
          emit('departmentAjax', res.data.deptName)
          formState.deptName = res.data.deptName
          if (res.data.workAreaName) {
            // 工区tag
            formState.dynamicTags = res.data.workAreaName.split(',')
          }
        }
      } else {
        formState.deptName = '' // 运维部门名称初始化
        formState.dynamicTags = [] // tag数组初始化
      }
    }

    // 提交前
    const updOrEditSubmit = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          // 数组转字符串
          formState.workAreaName = formState.dynamicTags?.join(',')
          // 部门字转id
          props.department?.forEach((item) => {
            if (item.title === formState.deptName) {
              formState.deptId = item.id
            }
          })
          // 工区字转id
          for (let i = 0; i < props.addList!.length; i++) {
            const item = props.addList![i]
            for (let j = 0; j < formState.dynamicTags!.length; j++) {
              const element = formState.dynamicTags![j]
              if (item.name === element) {
                formState.workAreaId += `${item.id},`
              }
            }
          }
          // 删最后一次加的逗号
          formState.workAreaId = formState.workAreaId?.slice(0, formState.workAreaId.length - 1)

          if (props.title === '新增运维部门管理') {
            addSubmit()
          }
          if (props.title === '编辑运维部门管理') {
            editSubmit()
          }
        } else {
          return false
        }
      })
    }

    // 新增->确定
    const addSubmit = async () => {
      const res = await store.dispatch('order/PostDeptConfigAdd', formState)
      if (res?.code === 200) {
        emit('departmentAjax') // 更新部门、部门是否可选
        emit('refreshTable') // 刷新列表
        handleCloseModal()
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
      } else {
        ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
      }
    }

    // 编辑->确定
    const editSubmit = async () => {
      const res = await store.dispatch('order/PostDeptConfigUpdate', formState)
      if (res?.code === 200) {
        emit('departmentAjax') // 更新部门、部门是否可选
        emit('refreshTable') // 刷新列表
        handleCloseModal()
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
      } else {
        ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
      }
    }

    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    // 关tag
    const closeTag = (tag: string) => {
      formState.dynamicTags?.splice(formState.dynamicTags.indexOf(tag), 1)
    }

    // 添加对应工区
    const addDynamic = (value: { name: string }) => {
      if (value && formState.dynamicTags?.indexOf(value.name) === -1) {
        // 排重
        formState.dynamicTags.push(value.name)
      }
    }

    // 新增/编辑 对应工区列表
    const dynamicColumns: TableColumnProps<operationsManageTableListDataItemType>[] = [
      {
        label: '',
        prop: 'name',
        minWidth: 90,
        align: 'left',
        showOverflowTooltip: true
      },
      {
        label: '',
        prop: 'options',
        minWidth: 90,
        align: 'right',
        render: ({ row }) => {
          return (
            <>
              {row && (
                <ElSpace>
                  <ElLink type="primary" disabled={row.ifDisabled} onClick={() => addDynamic(row)}>
                    <ElIcon size="large">
                      <CirclePlusFilled />
                    </ElIcon>
                  </ElLink>
                </ElSpace>
              )}
            </>
          )
        }
      }
    ]

    return () => {
      const { title, visible } = props

      return (
        <ElDialog
          title={title}
          modelValue={visible!}
          append-to-body
          width="400px"
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
        >
          <ElForm
            ref={ruleFormRef}
            model={formState}
            label-width="120px"
            class={styles['operationsManage-dialog']}
          >
            <ElFormItem
              label="运维部门名称"
              prop="deptName"
              rules={[{ required: true, message: '请选择运维部门', trigger: 'change' }]}
            >
              <ElSelect v-model={formState.deptName} placeholder="请选择运维部门" clearable>
                {props.department?.map((item) => (
                  <ElOption
                    label={item.title}
                    value={item.title}
                    disabled={item.ifDisabled}
                  ></ElOption>
                ))}
              </ElSelect>
            </ElFormItem>
            {/* 对应工区 */}
            <ElFormItem
              label="选择对应工区"
              prop="dynamicTags"
              rules={[{ required: true, message: '请选择对应工区', trigger: 'change' }]}
            >
              <div class={styles['operationsManage-tags']}>
                {formState.dynamicTags?.map((tag) =>
                  tag === '' ? (
                    <span></span>
                  ) : (
                    <ElTag
                      class={styles['tags-spacing']}
                      closable
                      disableTransitions={false}
                      onClose={() => closeTag(tag)}
                    >
                      {tag}
                    </ElTag>
                  )
                )}
              </div>
            </ElFormItem>
            <ElFormItem class={styles['operationsManage-dynamic']}>
              <ElScrollbar class={styles['dynamic-scrollbar']}>
                <ProSaasTable<operationsManageTableListDataItemType>
                  className={styles['dynamic-table']}
                  ref={dynamicProSaasTableRef}
                  columns={dynamicColumns}
                  data={props.addList} // 由于要给行加字段 所以未用dispatchType
                  showHeader={false}
                  needPagination={false}
                />
              </ElScrollbar>
            </ElFormItem>
            <div class={styles['confirm-button']}>
              <ElButton class={styles['confirm-button-cancel']} plain onClick={handleCloseModal}>
                取 消
              </ElButton>
              <ElButton
                class={styles['confirm-button-submit']}
                type="primary"
                onClick={() => updOrEditSubmit(ruleFormRef.value)}
              >
                确 定
              </ElButton>
            </div>
          </ElForm>
        </ElDialog>
      )
    }
  }
})
